package cn.crawler.app.web.modules.controllers.platform.sys;

import cn.crawler.app.sys.modules.models.SysIPTables;
import cn.crawler.app.sys.modules.services.SysIPTablesService;
import cn.crawler.framework.base.model.enums.BizExceptionEnum;
import cn.crawler.framework.util.Result;
import com.alibaba.dubbo.config.annotation.Reference;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.nutz.dao.Cnd;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.lang.Times;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;

import javax.servlet.http.HttpServletRequest;

/**
 * @author zl
 * @date 2020/6/30 9:39
 */
@IocBean
@At("/platform/sys/ip/tables")
public class SysIPTablesController {

    @Inject
    @Reference
    private SysIPTablesService sysIPTablesService;

    @At("")
    @Ok("beetl:/platform/sys/ip/index.html")
    @RequiresPermissions("sys.manager.ip.tables")
    public void index(HttpServletRequest req) {

    }

    @At
    @Ok("json:full")
    @RequiresPermissions("sys.manager.ip.tables")
    public Object data(@Param("searchKeyword") String searchKeyword,
                       @Param("searchDate") String[] searchDate,
                       @Param("pageNumber") int pageNumber,
                       @Param("pageSize") int pageSize) {
        Cnd cnd = Cnd.NEW();
        if (Strings.isNotBlank(searchKeyword)) {
            cnd.and("ip", "like", "%" + searchKeyword + "%");
        }
        if (searchDate != null && searchDate.length > 0) {
            cnd.and("ctAt", ">=", Times.d2TS(Times.D(searchDate[0])))
                    .and("ctAt", "<=", Times.d2TS(Times.D(searchDate[1])));
        }
        cnd.orderBy("ctAt", "desc");
        return Result.success().addData(sysIPTablesService.listPage(pageNumber, pageSize, cnd));
    }

    @At
    @Ok("json:full")
    @RequiresPermissions("sys.manager.ip.tables.edit")
    public Object add(@Param("..") SysIPTables sysIPTables) {
        if(null != sysIPTablesService.fetch(Cnd.where("ip", "=", sysIPTables.getIp()))){
            return Result.error(BizExceptionEnum.IP_EXISTS);
        }
        sysIPTablesService.add(sysIPTables);
        return Result.success();
    }

    @At
    @Ok("json:full")
    @RequiresPermissions("sys.manager.ip.tables.edit")
    public Object update(@Param("..") SysIPTables sysIPTables) {
        sysIPTablesService.update(sysIPTables);
        return Result.success();
    }

    @At
    @Ok("json:full")
    @RequiresPermissions("sys.manager.ip.tables.edit")
    public Object del(@Param("id") String id) {
        sysIPTablesService.del(id);
        return Result.success();
    }

}
